﻿using System;
using System.Collections.Generic;
using System.Reflection;
namespace Bridge.Base.Utilities
{
    using log4net;

    /// <summary>
    /// Extensions for <see cref="Type"/>
    /// </summary>
    public static class TypeExtensions
    {
        /// <summary>
        /// Gets the compatible types in all loaded assemblies.
        /// </summary>
        /// <param name="self"><see cref="Type"/> to compare.</param>
        /// <returns>List of <see cref="Type"/>s found.</returns>
        public static IEnumerable<Type> GetCompatibleTypes(this Type self)
        {
            List<Type> types = new List<Type>();
            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                try
                {
                    foreach (Type type in assembly.GetTypes())
                    {
                        if (self.IsAssignableFrom(type) && !type.IsAbstract)
                        {
                            types.Add(type);
                        }
                    }
                }
                catch (ReflectionTypeLoadException ex)
                {
                    LogManager.GetLogger("Bridge.Base.Utilities").Warn(string.Format("Unable to load types from {0}.", assembly.FullName), ex);
                }

            }
            return types;
        }
    }
}
